<template>
  <div class="container">
    <div class="content">
      <div class="title">
        <SvgIcon name="edit" size="18px"></SvgIcon>
        <span>&nbsp;店铺经营配置更新</span>
      </div>
      <div class="body">
        <el-form style="width: 700px" :model="form" label-width="auto" label-position="right" size="default">
          <el-form-item label="店铺类型" prop="shopCategory">
            <el-select placeholder="类型选择" v-model="form.shopCategoryId" :fit-input-width="true">
              <el-option v-for="item in shopCategoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="店铺位置">
            <div style="flex-grow: 1">
              <region ref="regionRef" v-model="form" v-model:regionLabel="form" class="children-item" />
              <el-input type="text" placeholder="补充店铺详细地址..." class="children-item" v-model="form.addressDescribe"> </el-input>
              <BMap
                @mousemove="isMapEditMode = true"
                @mouseout="isMapEditMode = false"
                :zoom="12"
                height="300px"
                :center="{ lng: form.longitude, lat: form.latitude }"
                ref="map"
              >
                <BZoom :offset="{ x: 20, y: 20 }" />
                <template v-if="circleVisibility && form.longitude && form.latitude && form.businessScope">
                  <BCircle
                    @lineupdate="onLineUpdate"
                    ref="circleRef"
                    enableEditing
                    stroke-style="solid"
                    strokeColor="#00f700"
                    fillColor="#00f700"
                    :fillOpacity="0.1"
                    :strokeWeight="1.5"
                    :center="{ lng: form.longitude, lat: form.latitude }"
                    :radius="form.businessScope * 1000"
                  />
                </template>
              </BMap>
            </div>
          </el-form-item>
          <el-form-item label="经营范围">
            <div class="in-a-line">
              <el-input type="number" v-model.number="form.businessScope"></el-input>
              <span>&nbsp;km</span>
            </div>
          </el-form-item>
          <el-form-item label="经营方式">
            <el-checkbox-group v-model="form._businessType" size="small">
              <el-checkbox :value="ReceivingMethodType.SHOP_EAT" label="店食" border />
              <el-checkbox :value="ReceivingMethodType.SELF_PICKUP" label="自提" border />
              <el-checkbox :value="ReceivingMethodType.DELIVERY" label="配送" border />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="配送方式">
            <el-radio-group v-model="form.deliveryMethod" size="small">
              <el-radio :value="DeliveryMethodType.PLATFORM" label="平台配送" border />
              <el-radio :value="DeliveryMethodType.MERCHANT_SELF_DELIVERY" label="商家自配" border />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="最低起送">
            <div class="in-a-line"><el-input type="number" v-model.number="form.minimumDeliveryAmount" />&nbsp;元</div>
          </el-form-item>
          <el-form-item label="餐盒费用">
            <div class="in-a-line"><el-input type="number" v-model.number="form.packingFee" />&nbsp;元</div>
          </el-form-item>
          <el-form-item label="区域配送时间效率">
            <div class="in-a-line"><el-input type="number" v-model.number="form.deliveryTimePerKm" />&nbsp;分钟/km</div>
          </el-form-item>
          <el-form-item label="制作餐食所需时间">
            <div class="in-a-line"><el-input type="number" v-model.number="form.makeTime" />&nbsp;分钟</div>
          </el-form-item>
          <el-form-item label="允许提前预定的天数">
            <div class="in-a-line"><el-input type="number" v-model.number="form.advanceBookingDays" />&nbsp;天</div>
          </el-form-item>
          <el-form-item label="向用户收取配送费用">
            <div class="in-a-line">
              <el-input type="number" v-model.number="form.deliveryFee" />&nbsp;元 &nbsp;
              <el-tooltip class="box-item" effect="dark" content="由商家自行设置并负责（商家需承担多出部分）" placement="top-start">
                <svgIcon name="heed"></svgIcon>
              </el-tooltip>
            </div>
          </el-form-item>

          <el-form-item label="&nbsp;">
            <el-button @click="cancelOperation">取消</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, watch, nextTick, Ref } from 'vue'
import ComponentHat from '@/plugins/type'
import router from '@/router'
const { $API, $modal } = <ComponentHat>getCurrentInstance().proxy
import { ShopCategory } from '@/types/response/shop-category'
import { ShopBusinessConfig } from '@/types/response/shop'
import region from '@/components/region/index.vue'
import { BMap, useAddressGeocoder, Point, usePointGeocoder, PointGeocoderResult } from 'vue3-baidu-map-gl'
import { debounce } from '@/utils/debounce'
import { ReceivingMethodType } from '@/enums/ReceivingMethodType'
import { DeliveryMethodType } from '@/enums/DeliveryMethodType'
import { CoordType } from '@/types/conduit/GeoCoordinates'
import { transformGCJ02ToBD09 } from '@/utils/coordinateConvert'
const shopCategoryList = ref<ShopCategory[]>([])
const form = ref(new ShopBusinessConfig())
const circleRef = ref()
// 区域选择器实例
const regionRef = ref()
// 文字 parse 位置信息
const map = ref()
const { get, point, isLoading } = useAddressGeocoder<Point>(() => map.value.resetCenter())

function refreshMarker() {
  if (form.value.districtName != null) {
    get(
      `${form.value.districtName ?? ''}${form.value.addressDescribe ?? ''}` ?? '政府',
      `${form.value.provinceName ?? ''}${form.value.cityName ?? ''}`
    )
  }
}
// 地理位置编辑模式
const isMapEditMode = ref(false)

// 当form圆的相关参数修改时同步刷新
const circleVisibility = ref(false)

// 刷新圆
watch(
  () => [form.value.longitude, form.value.latitude, form.value.businessScope],
  ([lng, lat, businessScope]) => {
    if (lng && lat && businessScope) {
      circleVisibility.value = false
      nextTick(() => (circleVisibility.value = true))
    }
  },
  { deep: true, immediate: true }
)
// 当地理名称改变时-point就会改变有值时修改form
watch(
  () => point.value,
  (newVal) => {
    if (newVal && newVal.lng && newVal.lat) {
      form.value.longitude = newVal.lng
      form.value.latitude = newVal.lat
    }
  }
)

// 请求基本信息进行回显
onMounted(async () => {
  const result = await Promise.all([$API.shopCategory.listAll(), $API.shop.shopBusinessConfig()])
  shopCategoryList.value = result[0].data
  form.value = result[1].data
  // 兼容回显
  form.value._businessType = (form.value.businessType ?? '').split(',').map((item) => parseInt(item))
  const targetGEO = transformGCJ02ToBD09(form.value.longitude, form.value.latitude)
  form.value.longitude = targetGEO[0]
  form.value.latitude = targetGEO[1]
  watch(
    () => [form.value.districtName, form.value.addressDescribe],
    () => refreshMarker(),
    { deep: true, immediate: false }
  )
})

// 当圆被编辑->修改form
const refreshDebouncePositionUpdate = debounce((lng: number, lat: number, radius: number) => {
  form.value.longitude = lng
  form.value.latitude = lat
  // 由于存在地图一些事件没有反应（失效）难以实现下面，会导致圆被编辑时，无法改变地理编码信息也就是只能进行微调
  // 位置名也需要同步修改-获取经纬度所在的地理code
  // const { get, result, isLoading } = usePointGeocoder<PointGeocoderResult[]>(
  //   {},
  //   (result: Ref<PointGeocoderResult | PointGeocoderResult[] | null>) => {
  //     // 这里为什么用any，因为PointGeocoderResult类型中没有定义我们需要content属性，而实际是有的，应该是作用没有加进来
  //     const resultData = (result.value as any[])[0]
  //     const districtCode = resultData.content.address_detail.adcode as number
  //     const areaCodes = parseParentCodeByDistrictCode(districtCode)
  //     Object.assign(form.value, areaCodes)
  //     // 使重新适应
  //     regionRef.value.adaptation()
  //   }
  // )
  // get([{ lng, lat }])

  form.value.businessScope = radius
}, 460)

// const restore = debounce(() => (isNeedIgnoreCircleEditEvent.value = true), 100)
function onLineUpdate(e: { target: { latLng: { lng: number; lat: number }; radius: number } }) {
  if (!isMapEditMode.value) return
  const { latLng, radius } = e.target
  if (latLng?.lng && latLng?.lat && radius) {
    refreshDebouncePositionUpdate(latLng.lng, latLng.lat, parseFloat((radius / 1000).toFixed(1)))
  }
}
async function onSubmit() {
  // 提交前将值处理成后端需要的再提交
  form.value.businessType = form.value._businessType.join(',')
  console.log('提交的表单信息：', form.value)
  // 提交指定的坐标体系
  form.value.coordinateType = CoordType.BD09
  // 提交
  const result = await $API.shop.updateShopBusinessConfig(form.value)
  if (result.success) {
    $modal.msgSuccess('修改成功')
    router.back()
  } else {
    $modal.msgError('修改失败!' + result.message)
  }
}
function cancelOperation() {
  // 取消修改-就返回
  router.back()
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;

  .content {
    display: flex;
    overflow: auto;
    padding: 20px;
    width: 100%;
    height: 100%;
    background-color: #fff;
    flex-direction: column;
    box-sizing: border-box;

    .title {
      display: flex;
      align-items: center;
      padding: 0 0 40px;
      font-size: 18px;
      font-weight: bold;
    }

    .body {
      display: flex;
      justify-content: center;

      .children-item {
        margin-bottom: 10px;
      }

      .in-a-line {
        display: flex;
        align-items: center;
        white-space: nowrap;
      }
    }
  }
}
</style>
